<template>
  <Panel title="连接管道" :data="data">
    <PipePathProps
      v-model:isFloating="innerIsFloating"
      v-model:isReverse="innerIsReverse"
      v-model:pipePathStyle="innerStyle"
      v-model:speed="innerSpeed"
      :type="type"
    />
  </Panel>
</template>
<script setup lang="ts">
import { computed, ref, watch } from "vue";
import type { AttrItem, PipePathStyle } from "./types";
import { PipePathPoint, PipePathSpeed, PipePathType } from "/@/components/types";
import { calc2pointDistance } from "/@/utils/draw";
import Panel from "./Panel.vue";
import PipePathProps from "./PipePathProps.vue";

const props = defineProps<{
  points: PipePathPoint[];
  isFloating: boolean;
  isReverse: boolean;
  pipePathStyle: PipePathStyle;
  type: PipePathType;
  speed: PipePathSpeed;
  setFloating: (isFloating: boolean) => void;
  setReverse: (isReverse: boolean) => void;
  setStyle: (style: PipePathStyle) => void;
  setSpeed: (val: PipePathSpeed) => void;
}>();

function getPartLen(points: PipePathPoint[]) {
  let len = 0;
  for (let i = 0; i < points.length - 1; i++) {
    len += calc2pointDistance(points[i], points[i + 1]);
  }
  return len;
}

const data = computed<AttrItem[]>(() => {
  let sumLen = 0;
  let pointsNum = 0;
  let partPoints: PipePathPoint[] = [];
  props.points.forEach((p) => {
    if (p.isParentNode) {
      sumLen += getPartLen(partPoints);
      partPoints = [];
    } else {
      pointsNum++;
    }
    partPoints.push(p);
  });
  if (partPoints.length > 1) {
    sumLen += getPartLen(partPoints);
  }
  return [
    { name: "节点数量", value: pointsNum },
    { name: "管道总长度", value: Math.round(sumLen), unit: "px" },
  ];
});

const innerStyle = ref<PipePathStyle>({ ...props.pipePathStyle });
watch(
  innerStyle,
  (v) => {
    props.setStyle(v);
  },
  {
    deep: true,
  }
);
watch(
  () => props.pipePathStyle,
  (v) => {
    innerStyle.value = v;
  }
);
const innerIsFloating = ref(props.isFloating);
watch(innerIsFloating, (v) => {
  props.setFloating(v);
});
watch(
  () => props.isFloating,
  (v) => {
    innerIsFloating.value = v;
  }
);
const innerIsReverse = ref(props.isReverse);
watch(innerIsReverse, (v) => {
  props.setReverse(v);
});
watch(
  () => props.isReverse,
  (v) => {
    innerIsReverse.value = v;
  }
);
const innerSpeed = ref(props.speed);
watch(innerSpeed, (v) => {
  props.setSpeed(v);
});
watch(
  () => props.speed,
  (v) => {
    innerSpeed.value = v;
  }
);
</script>
